package com.oneplatform.organisation.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesuite.common.JeesuiteBaseException;
import com.jeesuite.common.model.SelectOption;
import com.jeesuite.security.client.LoginContext;
import com.jeesuite.springweb.model.WrapperResponse;
import com.oneplatform.base.exception.ExceptionCode;
import com.oneplatform.organisation.dao.entity.PositionEntity;
import com.oneplatform.organisation.dto.param.PositionParam;
import com.oneplatform.organisation.service.PositionsService;

import io.swagger.annotations.ApiOperation;

/**
 * generated by www.jeesuite.com
 */
@Controller
@RequestMapping("/position")
public class PositionsController {

	private @Autowired PositionsService positionsService;

	@ApiOperation(value = "查询列表")
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public @ResponseBody WrapperResponse<List<PositionEntity>> findAll() {
		return new WrapperResponse<>(positionsService.findPositions());
	}

	@ApiOperation(value = "新增")
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public @ResponseBody WrapperResponse<String> addPosition(@RequestBody PositionParam param) {
		if(StringUtils.isBlank(param.getName())){
			throw new JeesuiteBaseException(ExceptionCode.REQUEST_PARAM_REQUIRED.code, "请填写公司名");
		}
		PositionEntity entity = new PositionEntity();
		entity.setName(param.getName());
		entity.setCreatedAt(new Date());
		entity.setCreatedBy(LoginContext.getIntFormatUserId());
		positionsService.addPositions(entity);

		return new WrapperResponse<>();
	}


	@ApiOperation(value = "删除账户")
	@RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
	public @ResponseBody WrapperResponse<String> deletePosition(@PathVariable("id") int id) {
		positionsService.deletePositions(id);
		return new WrapperResponse<>();
	}
	
	@ApiOperation(value = "下拉选项")
	@RequestMapping(value = "options", method = RequestMethod.GET)
	public @ResponseBody WrapperResponse<List<SelectOption>> getOptions() {
		List<PositionEntity> positions = positionsService.findAll();
		List<SelectOption> opts = new ArrayList<>();
		for (PositionEntity position : positions) {
			opts.add(new SelectOption(String.valueOf(position.getId()), position.getName()));
		}
		
		return new WrapperResponse<>(opts);
	}

}
